﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace BookManege.service
{
    internal class DatabaseUtil
    {
        public static MySqlConnection GetMysqlConnection()
        {
            //string mysql = "server=47.109.31.54;database=book_manege;user=book_manege;password=123456";
            string mysql = "server=localhost;database=book_manege;user=root;password=123456";
            MySqlConnection mysqlConn = new (mysql);
            mysqlConn.Open();
            return mysqlConn;
        }
        //公共查询工具
        public static object SelectUtil(string sql)
        {
            using (MySqlCommand mySqlCommand = new(sql, GetMysqlConnection()))
            {
                MySqlDataReader reader = mySqlCommand.ExecuteReader();
                try
                {
                    reader.Read();
                    return reader[0];
                }catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    reader.Close();
                }
            }
        }
        public static DataTable GetDataTable(string sql)
        {
            DataTable dataTable = new();
            //将数据填充到MySqlDataAdapter，再填充到dataSet才可以绑定数据
            using (MySqlDataAdapter mySqlDataAdapter = new(sql, GetMysqlConnection()))
            {
                mySqlDataAdapter.Fill(dataTable);
                return dataTable;
            }

        }
        public static int MyExecuteNonQuery(string sql)
        {
            using MySqlCommand mySqlCommand = new(sql, GetMysqlConnection());
            return mySqlCommand.ExecuteNonQuery();
        }
    }
}
